/**
 * Creat by TanLei
 * Description:
 * User:86183
 * Date:2022-05-13
 * Time:12:26
 */
class MyBlockQueue {
    private int[] items = new int[1000];

    private int size = 0;

    private int head = 0;

    private int tail = 0;

    private Object locker = new Object();

    public void put(int value) throws InterruptedException {
        synchronized (locker) {
            if (size == items.length) {
                //队列满了出发阻塞操作
                locker.wait();
                return;
            }
            items[tail] = value;
            tail++;
            if (tail >= items.length) {
                tail = 0;
            }
            //不推荐
            //tail = tail % items.length;
            size++;
            //唤醒take的阻塞等待的地方
            locker.notify();
        }
    }

    public Integer take() throws InterruptedException {
        synchronized (locker) {
            if (size == 0) {
                //return null;
                locker.wait();
            }
            int ret = items[head];
            head++;
            if (head >= items.length) {
                head = 0;
            }
            size--;
            locker.notify();
            return ret;
        }
    }

}

public class Demo22 {
    private static MyBlockQueue queue = new MyBlockQueue();

    public static void main(String[] args) {
//        MyBlockQueue myBlockQueue = new MyBlockQueue();
//        myBlockQueue.put(1);
//        myBlockQueue.put(2);
//        myBlockQueue.put(3);
//        myBlockQueue.put(4);
//        int ret = 0;
//        ret = myBlockQueue.take();
//        System.out.println(ret);
//        ret = myBlockQueue.take();
//        System.out.println(ret);
//        ret = myBlockQueue.take();
//        System.out.println(ret);
//        ret = myBlockQueue.take();
//        System.out.println(ret);

        Thread produce = new Thread(() -> {
            int n = 1;
            while (true) {
                try {
                    queue.put(n);
                    System.out.println("生产者生产了：" + n);
                    n++;
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        produce.start();

        Thread customer = new Thread(() -> {
            while (true){
                try {
                    int n = queue.take();
                    System.out.println("消费者消费了"+n);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start();
    }
}
